import logging
from app.core.config import settings
from app.db.models.user import User

logger = logging.getLogger(__name__)

async def send_email_async(to: str, subject: str, body: str):
    """Simulates sending an email asynchronously."""
    
    # Check if SMTP settings are configured (basic check)
    if not all([settings.SMTP_HOST, settings.SMTP_PORT, settings.SMTP_USER, settings.SMTP_PASSWORD, settings.EMAILS_FROM_EMAIL]):
        logger.warning(f"SMTP not configured. Skipping email to {to} with subject: {subject}")
        logger.info(f"--- Email Content ---")
        logger.info(f"To: {to}")
        logger.info(f"Subject: {subject}")
        logger.info(f"Body:\n{body}")
        logger.info(f"--- End Email Content ---")
        return # Don't attempt to send if not configured

    # --- Placeholder/Simulation --- 
    logger.info(f"Simulating sending email to: {to}")
    logger.info(f"Subject: {subject}")
    logger.info(f"Body: {body[:100]}...")
    await asyncio.sleep(0.5) # Simulate network delay
    logger.info(f"Email simulation complete for {to}.")
    # --- End Placeholder ---

    # --- Real Email Sending Logic (e.g., using aiosmtplib or fastapi-mail) ---
    # Replace placeholder with actual implementation if needed.
    # Example with fastapi-mail (requires installation and setup):
    # from fastapi_mail import FastMail, MessageSchema, ConnectionConfig
    # 
    # conf = ConnectionConfig(
    #     MAIL_USERNAME = settings.SMTP_USER,
    #     MAIL_PASSWORD = settings.SMTP_PASSWORD,
    #     MAIL_FROM = settings.EMAILS_FROM_EMAIL,
    #     MAIL_PORT = settings.SMTP_PORT,
    #     MAIL_SERVER = settings.SMTP_HOST,
    #     MAIL_STARTTLS = True, # Or False based on provider
    #     MAIL_SSL_TLS = False, # Or True based on provider
    #     USE_CREDENTIALS = True,
    #     VALIDATE_CERTS = True
    # )
    # 
    # message = MessageSchema(
    #     subject=subject,
    #     recipients=[to],
    #     body=body,
    #     subtype="html" # Or "plain"
    # )
    # 
    # fm = FastMail(conf)
    # try:
    #     await fm.send_message(message)
    #     logger.info(f"Successfully sent email to {to} with subject: {subject}")
    # except Exception as e:
    #     logger.exception(f"Failed to send email to {to}. Error: {e}")
    #     # Decide if you want to raise an error or just log
    # --- End Real Email Example ---

async def send_verification_email(user: User):
    """Sends the email verification email to a user."""
    # TODO: Generate a secure, time-limited verification token
    # Store it temporarily (e.g., cache or DB) associated with the user ID
    verification_token = "generate_a_real_secure_token_here"
    verification_url = f"http://localhost:8000/auth/verify-email?token={verification_token}" # Adjust domain/port
    
    subject = "请验证您的邮箱地址"
    body = f"""
    <p>您好 {user.username},</p>
    <p>感谢您的注册！请点击以下链接以激活您的账户:</p>
    <p><a href="{verification_url}">验证邮箱</a></p>
    <p>如果您没有注册，请忽略此邮件。</p>
    """
    await send_email_async(to=user.email, subject=subject, body=body)

async def send_password_reset_email(user: User):
    """Sends the password reset email to a user."""
    # TODO: Generate a secure, time-limited password reset token
    reset_token = "generate_another_secure_token_here"
    reset_url = f"http://localhost:8000/reset-password?token={reset_token}" # Adjust frontend URL

    subject = "重置您的密码"
    body = f"""
    <p>您好 {user.username},</p>
    <p>您请求了密码重置。请点击以下链接设置新密码:</p>
    <p><a href="{reset_url}">重置密码</a></p>
    <p>此链接将在短时间内失效。如果您没有请求重置密码，请忽略此邮件。</p>
    """
    await send_email_async(to=user.email, subject=subject, body=body)

# Need to import asyncio for the placeholder
import asyncio
